<template>
    <div>
        <el-form :model="param" label-width="100px"  ref="logAllSearchForm" :rules="rules" >
            <el-row>
                <el-col :span="6">
                    <el-form-item label="应用" prop="appId">
                        <el-select v-model="param.appId"
                                   filterable
                                   remote
                                   style="width: 90%"
                                   :remote-method="getlistOption"
                                   placeholder="请选择应用">
                            <el-option
                                    v-for="item in this.listOption"
                                    :key="item.id"
                                    :label="item.appName"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="文件" prop="fileName">
                        <el-autocomplete
                                style="width: 90%"
                                v-model="param.fileName"
                                :fetch-suggestions="(queryString,cb)=> {return querySearch(queryString,cb,'fileName')}"
                                placeholder="可以使用模糊匹配*"
                        ></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="前N行(全文0)">
                        <el-input-number   v-model="param.endNum" controls-position="right" placeholder="文件前n行" :step="500"  :min="0" ></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="4" >
                    <el-form-item label="后N行" prop="tailNum">
                        <el-input-number   v-model="param.tailNum" controls-position="right" placeholder="文件后n行" :step="500"  :min="1" ></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="logSearch">查询</el-button>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="目录">
                        <el-link v-for="(folder,index) in folderList" type="primary" @click="selectFolder(index)" :underline="false" :disabled="folderList.length==1">{{folder}}></el-link>
                    </el-form-item>

                </el-col>
                <el-col :span="4">
                    <el-button type="primary"  @click="fileNameSearch" :disabled="isEmpty(param.appId)">查文件</el-button>
                </el-col>
            </el-row>
        </el-form>

        <el-card class="log-search-card log-search-card-top" v-if="fileNameList && fileNameList.length >0" v-loading="fileNameLoading"  element-loading-spinner="el-icon-loading"
                 element-loading-background="rgba(0, 0, 0, 0.8)"  element-loading-text="拼命加载中">
            <el-collapse v-model="fileActiveNames" >
                <el-collapse-item v-if="fileNameList && fileNameList.length >0"  title="系统文件名称" name="0">
                    <p v-for="(file,index) in fileNameList">
                        <el-link :icon="file.type ==0 ?'el-icon-folder':'el-icon-document'" type="primary" @click="selectFile(file.name,file.type)" :underline="false" >{{file.name}}</el-link>
                    </p>
                </el-collapse-item>
            </el-collapse>
        </el-card>
        <el-card class="log-search-card" v-loading="loading" element-loading-spinner="el-icon-loading"
                 element-loading-background="rgba(0, 0, 0, 0.8)"  element-loading-text="拼命加载中">
            <el-collapse v-model="activeNames">

                <el-collapse-item v-if="logInfoList.length >0"  v-for="(logInfo,index) in logInfoList" :title="'主机:'+logInfo.shellHost +' '+logInfo.logs.length +'行'" :name="index">
                    <p v-for="log in logInfo.logs" v-html="log" style="margin-top: 10px;margin-bottom: 10px;line-height: 19px"></p>
                </el-collapse-item>

                <div v-if="!logInfoList ||logInfoList.length ==0" style="height:60vh">
                    <h3>未查询到日志</h3>
                </div>
            </el-collapse>
        </el-card>


    </div>
</template>

<script>
    import {LogAllSearch,AppInfolistOption,SearchFileName} from "@/api"

    export default {
        name: "LogAllSearch",
        mounted() {
            this.getlistOption("");
            if(this.$route.query.appId){
                this.param.appId = Number.parseInt(this.$route.query.appId)
            }
            for(name in this.cacheData.cacheKey){
                this.getCache(name);
            }
        },
        methods:{
            getCache(name){
                let keywordCache = localStorage.getItem("logAllSearch" + name);
                keywordCache = JSON.parse(keywordCache)
                if(!keywordCache){
                    keywordCache =[]
                }
                this.cacheData.cacheItem[name] =keywordCache;
            },
            setCache(name){
                if(!this.param[name] ||!this.param[name].trim()){
                    return;
                }
                let restaurants = localStorage.getItem("logAllSearch"+name);
                let cacheMap = {"value":this.param[name].trim()};
                let cacheList = JSON.parse(restaurants)
                if(restaurants && restaurants.indexOf(JSON.stringify(cacheMap)) > -1){
                    for (let index in cacheList){
                        if(this.param[name].trim() == cacheList[index]["value"] && index ==0){
                            return;
                        }else if(this.param[name].trim() == cacheList[index]["value"]){
                            cacheList.splice(index, 1);
                            break
                        }
                    }
                }
                if(!cacheList ){
                    cacheList = []
                }
                cacheList.unshift(cacheMap);
                if(cacheList.length > this.cacheData.cacheKey[name]["num"]){
                    cacheList.pop()
                }
                this.cacheData.cacheItem[name] = cacheList;
                localStorage.setItem("logAllSearch"+name,JSON.stringify(cacheList));

            },
            getFolder(){
                let folder = "";
                //对目录地址拼接，如果是最后一个则
                this.folderList.forEach((fileName,index)=>{
                    if(index >0){
                        console.log(fileName)
                        folder += fileName;
                        folder += "/";
                    }
                });
                return folder;
            },
            selectFile(fileName,type){
                if(type == 1){
                    this.param.fileName = fileName;
                }else {
                    //文件夹
                    this.folderList.push(fileName)
                    //执行请求
                    this.fileNameSearch();
                }

            },
            selectFolder(index){
                this.folderList.splice(index+1)
                //执行请求
                this.fileNameSearch();
            },
            querySearch(queryString,cb,name) {
                var results = queryString ?  this.cacheData.cacheItem[name].filter(this.createFilter(queryString)) : this.cacheData.cacheItem[name];
                // 调用 callback 返回建议列表的数据
                cb(results);
            },
            createFilter(queryString) {
                return (restaurant) => {
                    return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },
            isEmpty(obj){
                if(typeof obj == "undefined" || obj == null || obj == ""){
                    return true;
                }else{
                    return false;
                }

            },
            fileNameSearch(){
                this.fileNameLoading = true;
                let folder = this.getFolder();
                //对目录地址拼接，如果是最后一个则

                var param = {
                    folder:escape(folder),
                    appId:this.param.appId
                };
                this.fileNameLoading = true;
                SearchFileName(param).then(result=>{
                    this.fileNameLoading = false;
                    if(result && result.codeStatus == 200){
                        this.fileNameList = result.data;
                        if(!this.fileNameList || this.fileNameList.length <0){
                            this.$success('提示', "不存在文件,请修改实例目录！");
                        }
                    }
                })
            },
            logSearch(){
                this.$refs.logAllSearchForm.validate((valid) => {
                    if(valid){
                        this.loading = true;
                        let folder = this.getFolder();
                        let param = JSON.parse(JSON.stringify(this.param))
                        param.fileName = folder+ param.fileName
                        LogAllSearch(param).then(result=>{
                            this.loading = false;
                            if(result && result.codeStatus == 200){
                                if( this.logInfoList && this.logInfoList.length >0){
                                    this.activeNames = [0]
                                }
                                this.logInfoList = result.data;
                                for(name in this.cacheData.cacheKey){
                                    this.setCache(name);
                                }
                            }

                        })
                    }

                })

            },
            getRemote(keyword){
                this.getlistOption(keyword)
            },
            getlistOption(keyword){
                this.optionLoading = true;
                AppInfolistOption(keyword).then(result=>{
                    this.optionLoading =false;
                    if(result && result.codeStatus == 200){
                        this.listOption = result.data;
                    }
                })

            },

        },

        data(){
            return {
                keyword:"",//查询应用关键词
                logInfoList:[],
                fileNameList:[],
                listOption:[],
                activeNames:[0],
                fileActiveNames:["0"],
                optionLoading:false,
                fileNameLoading:false,
                loading:false,
                folderList:["根目录"],
                cacheData:{
                    cacheItem:{},
                    cacheKey:{
                        "fileName":{num:10},
                    }
                },
                param:{
                    appId:"",
                    endNum:"",
                    fileName:'',
                    tailNum:"1000",

                },
                rules:{
                    appId: [
                        { required: true, message: '请选择应用', trigger: 'blur' }
                    ],
                    fileName: [
                        { required: true, message: '请输入文件名', trigger: 'change' }
                    ],
                    tailNum: [
                        { required: true, message: '请输入查询行数', trigger: 'change' }
                    ],
                    keyword: [
                        { required: true, message: '请输入关键字', trigger: 'change' }
                    ],
                    upLine: [
                        { required: true, message: '请输入查询命令', trigger: 'change' }
                    ],

                }
            }
        },

    }
</script>

<style >
    .log-search-card-top{
        margin-bottom: 20px;
    }

</style>